<template>
    <div class="table-toolbar">
      <div class="toolbar-container">
        <el-tabs v-if="hasSelectPermission && selectOptions.length > 0" 
                v-model="selectedValue" 
                class="system-tabs"
                @tab-click="handleTabClick">
                <el-tab-pane label="全部" :name="''">
                </el-tab-pane>
          <el-tab-pane v-for="item in selectOptions"
                      :key="item.value"
                      :label="item.label"
                      :name="item.value">
          </el-tab-pane>
        </el-tabs>

        <div class="search-area">
          <el-date-picker
            v-if="showDatePicker"
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :shortcuts="dateShortcuts"
            @change="handleDateChange"
            @clear="handleReset"
            clearable
          />
          
          <el-input 
            v-if="hasSearchPermission"
            v-model="searchKeyword" 
            :placeholder="placeholder" 
            clearable 
            size="default"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon>
                <Search />
              </el-icon>
            </template>
          </el-input>
          <div class="search-buttons" v-if="hasSearchPermission">
            <el-button-group class="crud-buttons">
              <el-button type="primary" size="default" @click="handleSearch">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button size="default" @click="handleReset">
                <el-icon><RefreshRight /></el-icon>
                重置
              </el-button>
            </el-button-group>
          </div>
        </div>
        <div class="right">
          <el-button-group>
            <template v-for="button in filteredButtons" :key="button.key">
              <el-button 
                v-if="hasButtonPermission(button.key)"
                :type="button.type as '' | 'primary' | 'success' | 'warning' | 'danger' | 'info'" 
                :disabled="getButtonDisabled(button.key)"
                size="default"
                @click="handleButtonClick(button.key)"
              >
                <el-icon>
                  <component :is="button.icon" />
                </el-icon>
                {{ button.text }}
              </el-button>
            </template>
          </el-button-group>
        </div>
      </div>
    </div>
  </template>
  
  <script lang="ts" id="table-toolbar" setup>
  //高级过滤是内嵌入方法，切换时回调方法和搜索一致handleSearch。
  import { ref, watch, computed } from 'vue'
  import { useRoute } from 'vue-router'
  import {
    Search,
    RefreshRight,
    Download,
    Printer,
    Plus,
    Edit,
    Delete,
    Switch
  } from '@element-plus/icons-vue'
  
  type ButtonKey = 'add' | 'edit' | 'delete' | 'export' | 'print'
  
  const buttons = [
    { key: 'add' as ButtonKey, text: '新增', icon: Plus, type: 'primary' },
    { key: 'edit' as ButtonKey, text: '编辑', icon: Edit, type: 'primary' },
    { key: 'delete' as ButtonKey, text: '删除', icon: Delete, type: 'danger' },
    { key: 'export' as ButtonKey, text: '导出', icon: Download, type: '' },
    { key: 'print' as ButtonKey, text: '打印', icon: Printer, type: '' },
    { key: 'virtual' as ButtonKey, text: '高级过滤', icon: Switch, type: 'primary' }
  ]
  
  const route = useRoute()
  
  interface SelectOption {
    value: string | number
    label: string
  }
  
  //可从业务层传入参数来表示是否显示，默认不显示，从路由级别重新构造，根据路由meta中的buttons过滤显示的按钮
  const props = withDefaults(defineProps<{
    placeholder?: string
    selectedCount?: number
    showOperations?: boolean
    selectOptions?: SelectOption[]
    selectPlaceholder?: string
    disabledOperations?: {
      edit: boolean
      delete: boolean
    }
    showDatePicker?: boolean
  }>(), {
    showOperations: true,
    selectOptions: () => [],
    selectPlaceholder: 'Select',
    showDatePicker: false
  })
  
  const emit = defineEmits(['search', 'reset', 'add', 'edit', 'delete', 'export', 'print', 'select-change', 'date-change'])
  
  const searchKeyword = ref('')
  const selectedValue = ref<string | number>('')
  const dateRange = ref<[string, string] | null>(null)
  
  // 日期选择器快捷方式
  const dateShortcuts = [
    {
      text: '最近一周',
      value: () => {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
        return [start, end]
      }
    },
    {
      text: '最近一个月',
      value: () => {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
        return [start, end]
      }
    },
    {
      text: '最近三个月',
      value: () => {
        const end = new Date()
        const start = new Date()
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
        return [start, end]
      }
    }
  ]
  
  // 根据路由meta中的buttons过滤显示的按钮
  const filteredButtons = computed(() => {
    const routeButtons = route.meta?.buttons || []
    return buttons.filter(button => routeButtons.includes(button.key))
  })
  
  // 检查按钮权限
  const hasButtonPermission = (buttonKey: ButtonKey) => {
    const routeButtons = route.meta?.buttons || []
    return routeButtons.includes(buttonKey)
  }
  
  // 监听选择值变化
  watch(selectedValue, (newValue) => {
    emit('select-change', newValue)
  })
  
  // 获取按钮禁用状态
  const getButtonDisabled = (buttonKey: ButtonKey) => {
    // 禁用导出和打印按钮（当没有选中行时）
    if ((buttonKey === 'export' || buttonKey === 'print') && 
        props.selectedCount === 0) {
      return true;
    }
    
    if (!props.disabledOperations) return false;
    return props.disabledOperations[buttonKey as keyof typeof props.disabledOperations] || false;
  }
  
  const handleSearch = () => {
    emit('search', searchKeyword.value)
  }
  
  const handleReset = () => {
    searchKeyword.value = ''
    selectedValue.value = ''
    dateRange.value = null
    emit('reset')
  }
  
  // 添加日期变化的处理方法
  const handleDateChange = (val: [string, string] | null) => {
    emit('date-change', val)
  }
  
  // 修改 handleButtonClick 方法，移除注释掉的调试信息
  const handleButtonClick = (buttonKey: ButtonKey) => {
    if ((buttonKey === 'export' || buttonKey === 'print') && 
        props.selectedCount === 0) {
      return;
    }
    emit(buttonKey);
  }
  
  // 修改权限检查计算属性
  const hasSearchPermission = computed(() => {
    const routeButtons = route.meta?.buttons || []
    return routeButtons.includes('search') || !route.meta?.buttons // 如果没有设置按钮权限，默认显示
  })
  
  const hasSelectPermission = computed(() => {
    const routeButtons = route.meta?.buttons || []
    return routeButtons.includes('select') || !route.meta?.buttons // 如果没有设置按钮权限，默认显示
  })
  const showDatePicker = computed(() => {
    const routeButtons = route.meta?.buttons || []
    return routeButtons.includes('datePicker') || !route.meta?.buttons // 如果没有设置按钮权限，默认显示
  })

  // 添加标签页点击处理函数
  const handleTabClick = (tab: any) => {
    emit('select-change', tab.props.name)
  }
  
  // 暴露给父组件的值
  defineExpose({
    selectedValue,
    searchKeyword,
    dateRange,
    handleDateChange
  })
  </script>
  
  <style lang="scss" scoped>
  .table-toolbar {
    .toolbar-container {
      display: flex;
      align-items: center;
      gap: 16px;
      flex-wrap: nowrap;

      .system-tabs {
        flex-shrink: 0;
        :deep(.el-tabs__header) {
          margin: 0;
          border-bottom: none;

          .el-tabs__nav-wrap {
            &::after {
              display: none;
            }

            .el-tabs__nav {
              border: none;
            }

            .el-tabs__item {
              padding: 0 12px;
              height: 32px;
              line-height: 32px;
              font-size: 14px;
              border: none;
              background: transparent !important;
              
              &.is-active {
                color: #409EFF;
                font-weight: 500;
              }

              &:not(.is-active) {
                color: #606266;
              }

              &:hover {
                color: #409EFF;
              }

              &:focus, &:active {
                background-color: transparent !important;
                outline: none;
              }
            }
          }
        }

        :deep(.el-tabs__content) {
          display: none;
        }
      }

      .search-area {
        display: flex;
        align-items: center;
        gap: 8px;
        flex-shrink: 0;
        flex-wrap: wrap;

        :deep(.el-date-editor.el-input__wrapper) {
          width: 240px;
        }

        .el-input {
          width: 200px;
        }

        .search-buttons {
          display: flex;
          gap: 8px;

          .el-button {
            .el-icon {
              margin-right: 4px;
            }
          }
        }
      }

      .right {
        display: flex;
        margin-left: auto;
        flex-shrink: 0;
      }
    }
  }
  </style>